// JavaScript Document

var events = {
	
	// stores a reference to the currently loaded article category for quick addition
    category_id: null,
	
    // stores a reference to the last selected category link
    lastCategoryLink: null,
	
	// ajax page to use for loading
	ajax_processor: 'ajax_pages/events.php',
	
    /**
	 * Setup the required controls to enable the AJAX functionalities and other UI controls
	 * work as expected
	 */
    init: function() {
		
        if( document.getElementById("EventDesc") != null ) {
			// make the event description field an html editor
			ui.htmlContentEditor("EventDesc");
			
			// add handler for making alias form of news title
			if( document.getElementById("EventAddForm") != null ) {
				$("#EventName").friendurl({id:'FriendlyURL'});
			}
			
			$("#Date, #StartDate, #EndDate").datepicker({
				dateFormat: 'yy-mm-dd',
				showOn: 'button',
				buttonImage: 'images/icons/calendar.png',
				buttonImageOnly: true,
				changeMonth: true,
				changeYear: true
			});
			
            // adjust the css of all the trigger buttons, since their sizes appear bigger than required
            $p.all("#startTrig, #endTrig, #dateTrig", function(el) {
                el.style.padding = "3px";
            });
			
            // show the current event duration panel
            showEventDurationArea();
			
        } else {
			
            $p.addEvent('delete-all-link', 'click', function() {
                events.deleteEvents();
            });
			
			$p.addEvent('add-cat-link','click',function() {
				events.showCategoryAddWindow();
			});
			
            $p.addEvent('del-cat-link', 'click', function() {
                events.deleteEventCategory();
            });
			
            $p.addEvent('add-cat-btn', 'click', function() {
                events.addNewCategory();
            });
			
			$p.addEvent('cancel-cat-btn', 'click', function() {
                events.hideCategoryAddWindow();
            });
			
            $p.all(".category-list li a", function(el) {
                el.onclick = function() {
                    // load the news in this category and indicate it as selected
                    events.loadEvents(this);
					
                    return false;
                };
						
            });
			
            // load the news in the first category, if we are not the list page
            var firstCat = $p.$(".category-list li:first-child a");
            if( firstCat != null ) {
                events.loadEvents( firstCat );
            } else {
                document.getElementById('event-content').innerHTML = '<span>No Event Categories Exist For This Site. Please Create Event Categories To Group Events</span>';
            }
        }
		
    },
	
    /**
     * Loads the list of events in the specified category
     *
     * @param catLink the link element representing the category
     * @param page an integer representing the page for which to load data for
     */
    loadEvents: function(catLink, page) {
        // if a category link is not specified, check if a previous one exists and use that instead
        if( catLink == null && events.lastCategoryLink != null ) {
            catLink = events.lastCategoryLink;
		
        // if one does not exist, then inform and exit
        } else if( catLink == null && events.lastCategoryLink == null) {
            alert('Cannot Load Events If Category Link Is Not Specified');
            return;
        }
		
        //clear any previously selected list items
        $p.all(".category-list li", function(li) {
            li.className = '';
        });
		
        // set a variable to determine the limit for the number of pages to load
        var limit = 25;
		
        var catName = catLink.innerHTML;
        var catId = catLink.id;
        catLink.parentNode.className = 'selected';
		
        // cache the currently selected category id
        events.category_id = catId;
		
        // cache the last category link
        events.lastCategoryLink = catLink;
		
        // update the article list header
        $p.$(".articles-pane .pane-header").innerHTML = 'Upcoming Events In ' + catName;
		
        // build the query to load the news based on the category id
        var query = "action=load_events&category=" + catId + "&limit=" + limit;
		
        // if a specific page is specified, then ammend the query to include that
        // also add the option to not reload the articles-total data so that the navigation
        // bar would not be regenerated
        if( page ) {
            query += "&start=" + page + "&no-total=true";
        }

        $p.setLoaderMessage("Loading News In " + catName + ". Please Wait...");
        $p.post('ajax_pages/events.php', query, function(data) {
			
			$p('#event-content').html(data);
			
            // obtain the information about the total number of articles in this category
            // and generate a dynamic list of page links
            if( document.getElementById("articles-total") ) {
                
                var total = document.getElementById("articles-total").value;
                var total_pages = Math.ceil((total / limit));
				
                // get the footer pane and clear the contents
                var paneFooter = $p.$(".articles-pane .pane-footer");
                paneFooter.innerHTML = "<b>Pages: </b> ";
				
                for(var i = 0; i < total_pages; i++) {
                    var a = document.createElement("a");
                    a.setAttribute("href","#");
                    a.id = "page-" + i;
                    a.className = "nav-link";
					
                    // if this is the first link, then indicate that this is the selected page
                    if(i == 0 ) {
                        a.className = "selected";
                    }
					
                    a.innerHTML = (i + 1);
					
                    // add the necessary callback to the link to enable page loading
                    a.onclick = function() {
                        $p.all(".pane-footer a", function(el) {
                            el.className = "nav-link";
                        });
						
                        this.className = "selected";
						
                        var p = this.id.split("-")[1];
                        events.loadEvents( events.lastCategoryLink, p);
                    };
					
                    paneFooter.appendChild( a );
                }
            }

            // register the checkAll checkbox to be able to select all displayed messages
            $p.addEvent('checkAll', 'click', function() {
				
                // select all input fields in table-cells in the data-table component
                $p.all(".cms-data-table td input[type=checkbox]", function(el) {
                    el.checked = $p.$('checkAll').checked;
                });
            });
			
            // register all edit-links
            $p.all(".cms-data-table .edit-link", function(el) {
                el.onclick = function(e) {
                    //news.editArticle( this.id );
                    location.href = '?edit&id=' + this.id;
                    return false;
                };
            });
						
            // register all edit-links
            $p.all(".cms-data-table .delete-link", function(el) {
                el.onclick = function(e) {
                    events.deleteEvent( this.id );
                    return false;
                };
            });
			
            // register all the publish or unpublish-links
            $p.all(".cms-data-table .cms-publish-link, .cms-data-table .cms-unpublish-link", function(el) {
                el.onclick = function() {
                    if( el.className == 'cms-publish-link' ) {
                        events.publishArticle('unpublish', this );
                    } else {
                        events.publishArticle('publish', this );
                    }
					
                    return false;
                };
            });
        });
    },
	
	publishArticle: function(action, linkEl) {
        var query = "action=" + action + "&id="	+ linkEl.id;
		
        $p.post(events.ajax_processor, query, null, function() {
            if( action == "publish" ) {
                linkEl.className = 'cms-publish-link';
                linkEl.title = 'Published (Click To Unpublish)';
                linkEl.onclick = function() {
                    events.publishArticle('unpublish', this);
                }
            } else {
                linkEl.className = 'cms-unpublish-link';
                linkEl.title = 'Unpublished (Click To Publish Now)';
                linkEl.onclick = function() {
                    events.publishArticle('publish', this);
                }
            }
        });
    },
	
    addNewCategory: function() {
        var query = "action=add_category&" + $p.buildQuery( $p.$("#catForm") );

        $p.all("#catForm input",function(el) {
            el.disabled = true;
        });
		
        // post the data to the server
        $p.post(events.ajax_processor, query, null, function(data) {
			
            if( JSON ) {
                var obj = JSON.parse(data);
                var a = document.createElement("a");
                a.id = obj.id;
                a.setAttribute("href","#");
                a.innerHTML = obj.categoryName;
                a.title = obj.categoryDesc;
                a.onclick = function() {
                    events.loadEvents(this);
                    return false;
                };
					
                var li = document.createElement("li");
                li.appendChild(a);
					
                $p.$(".category-list").appendChild(li);
				
                $p.hide("catAddDiv");
            }
			
            // re-enable the input fields
            $p.all("#catForm input",function(el) {
                el.disabled = false;
            });
        });
    },
	
    deleteEvent: function(article_id) {
        $p.showConfirmMessage({
            title: 'Confirm Article Delete',
            content: "Do you want to delete the specified articles from this site?",
            okButtonText: 'Continue Delete',
            okButtonAction: function() {
                var query = "action=delete_articles&article_ids=" + article_id;
                $p.post(events.ajax_processor, query, null, function() {
                    $p("#article-row-" + article_id ).remove();
                });
            }
        });
    },
	
    /**
	 * Deletes the currently selected (checked) articles in the article display list
	 *
	 */
    deleteEvents: function() {
        /**
		 * it would have been so much easier to use the following selector
		 * .cms-data-table td input[type=checkbox]:checked
		 * but IE8 does not support the :checked pseudo class, so we will need to 
		 * do the checking manually in order to be cross platform compartible
		 */
        var checks = $p.all(".cms-data-table td input[type=checkbox]");
		
        var checked = [];
        for(var i = 0, j = 0; i < checks.length; i++ ){
            if( checks[i].checked ) {
                checked[j++] = checks[i];
            }
        }
		
        if( checked.length == 0 ) {
            alert("Please Select Items To Delete");
            return;
        }
		
        var ids = "";
        for(var i = 0; i < checked.length; i++) {
            ids += checked[i].value;
			
            if( i < checked.length - 1) {
                ids += ",";
            }
        }
		
        $p.showConfirmMessage({
            title: 'Confirm Article Delete',
            content: "Do you want to delete the specified articles from this site?",
            okButtonText: 'Continue Delete',
            okButtonAction: function() {
                var query = "action=delete_articles&article_ids=" + ids;
                $p.post(events.ajax_processor, query, null, function() {
					
                    // select all checkbox fields in table-cells in the data-table component
                    $p.all(".cms-data-table td input[type=checkbox]", function(el) {
                        if( el.checked ) {
                            $p("#article-row-" + el.value ).remove();
                        }
                    });
					
                });
            }
        });
    },
	
    deleteEventCategory: function() {
        var lastCat = events.lastCategoryLink;
		
        $p.showConfirmMessage({
            title: "Confirm News Category Delete",
            content: "This will delete all Events in the <b>" + lastCat.innerHTML + "</b> category. "
            + "Do you want to continue the delete of this category?",
            okButtonText: "Delete Category",
			width: '400px',
            okButtonAction: function() {
                var query = "action=delete_category&category_id=" + events.lastCategoryLink.id ;
                $p.post(events.ajax_processor, query, null, function() {
                    events.lastCategoryLink.parentNode.removeChild( events.lastCategoryLink );
                });
            }
        });
    },
	
	showCategoryAddWindow: function() {
        //document.getElementById("catAddDiv").style.visibility = "visible";
        $p("#catAddDiv").show();
    },
	
    hideCategoryAddWindow: function() {
        //document.getElementById("catAddDiv").style.visibility = "hidden";
        $p("#catAddDiv").hide();
    }
};


function showCategoryAddWindow() {
    document.getElementById("catAddDiv").style.visibility = "visible";
}

function hideCategoryAddWindow() {
    document.getElementById("catAddDiv").style.visibility = "hidden";
}

function showCategoryEditWindow(id, catName, catDesc) {
    document.getElementById("EditCategoryName").value = catName;
    document.getElementById("EditCatDesc").value = catDesc;
    document.getElementById("EditCatID").value = id;
    document.getElementById("catEditDiv").style.visibility = "visible";
}

function hideCategoryEditWindow() {
    document.getElementById("catEditDiv").style.visibility = "hidden";
}

function showDateArea(area) {
    if( area == "#single" ) {
        $p("#period").hide();
    } else if( area == "#period" ) {
        $p("#single").hide();
    }
    
    $p(area).show();
}

function showEventDurationArea() {
    if(document.getElementById("singleCheck")) {
        if( document.getElementById("singleCheck").checked ) {
            showDateArea("#single");
        } else {
            showDateArea("#period");
        }
    }
}	
	
